<template>
  <div class="ai-chat-container">
    <div class="chat-wrapper">
      <div class="chat-header">
        <span class="model-title">Multimodal LLM 多图片对话</span>
      </div>

      <div class="chat-body" ref="chatBody">
        <div v-if="messages.length === 0" class="empty-state">
          <p>上传图片后开始与AI对话</p>
        </div>
        
        <!-- 显示所有用户消息和AI回复 -->
        <div v-for="(message, index) in messages" :key="index" class="chat-message-group">
          <!-- 用户消息 -->
          <div class="message-item user-message">
            <div class="message-avatar user">👤</div>
            <div class="message-content">
              <div class="message-bubble user-bubble">
                <div v-if="message.mergedImage" class="image-group">
                  <img :src="message.mergedImage" class="merged-image" alt="拼接的图片" />
                </div>
                
                <div v-if="message.userText" class="message-text user-text">
                  {{ message.userText }}
                </div>
              </div>
            </div>
          </div>

          <!-- AI 回复 -->
          <div class="message-item ai-message">
            <div class="message-avatar ai">🤖</div>
            <div class="message-content">
              <div class="message-bubble ai-bubble">
                <div v-if="message.isTemporary" class="loading-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <div v-else class="message-text ai-text" v-html="renderMarkdown(message.aiResponse)">
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input-area">
        <div class="chat-block">
          <textarea
            class="chat-input"
            v-model="inputText"
            placeholder="请输入文本(可以比较或分析多张图片)..."
            rows="3"
          ></textarea>
          <div class="input-actions">
            <button class="btn send-btn" @click="handleSend">发送</button>
          </div>
        </div>
        <div class="bottom-actions">
          <button class="btn regenerate-btn" @click="handleRegenerate">重新生成</button>
          <button class="btn clear-chat-btn" @click="handleClearChat">清空对话</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { concatenateImages } from '../utils/imageUtils';
import { callAIChat } from '../utils/api';
import { marked } from 'marked';

export default {
  name: 'AIChat',
  props: {
    uploadedImages: {
      type: Array,
      default: () => []
    },
    apiConfig: {
      type: Object,
      required: true
    },
    customPrompt: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      messages: [],
      isLoading: false,
      inputText: ''
    };
  },
  methods: {
    async handleSend() {
      if (!this.uploadedImages.length && !this.inputText.trim()) {
        alert('请至少上传一张图片或输入文本');
        return;
      }

      // 获取 base64 格式的图片数组
      const images = this.uploadedImages
        .filter(img => img && img.url)
        .map(img => img.base64 || img.url); // 优先使用明确的 base64 字段
      
      if (images.length > 0 || this.customPrompt || this.inputText) {
        // 保存拼接后的图片到消息中
        const userMessageText = [this.inputText].filter(Boolean).join('\n\n');
        
        // 拼接图片
        let mergedImageBase64 = null;
        if (images.length > 0) {
          mergedImageBase64 = await concatenateImages(images);
        }
        
        // 立即添加用户消息到聊天记录
        const newMessage = {
          mergedImage: mergedImageBase64, // 保存拼接后的图片
          userText: userMessageText,      // 合并用户的所有文本内容
          aiResponse: '',                 // 初始化为空
          isTemporary: true               // 标记为临时消息，表示还在等待AI回复
        };
        
        this.messages.push(newMessage);
        const messageIndex = this.messages.length - 1;
        
        // 滚动到底部
        this.$nextTick(() => {
          if (this.$refs.chatBody) {
            this.$refs.chatBody.scrollTop = this.$refs.chatBody.scrollHeight;
          }
        });
        
        // 设置加载状态
        this.isLoading = true;
        
        try {
          // 调用 AI 接口
          const aiResponse = await callAIChat(
            mergedImageBase64,
            this.customPrompt,
            this.inputText,
            {
              model: this.apiConfig.model,
              apiUrl: this.apiConfig.apiUrl
            }
          );

          // 更新消息中的AI回复
          this.$set(this.messages, messageIndex, {
            ...newMessage,
            aiResponse: aiResponse,
            isTemporary: false // 标记为非临时消息
          });

        } catch (error) {
          console.error('AI 调用失败:', error);
          
          // 更新消息中的错误信息
          this.$set(this.messages, messageIndex, {
            ...newMessage,
            aiResponse: `错误: ${error.message}`,
            isTemporary: false // 标记为非临时消息
          });

        } finally {
          this.isLoading = false;
          
          // 清空输入框（保留图片以便继续对话）
          this.inputText = '';
          
          // 在发送消息成功回复后清空图片列表
          // 注意：这里不直接清空uploadedImages，而是通过事件通知父组件
          this.$emit('clear-images');
          
          // 滚动到底部
          this.$nextTick(() => {
            if (this.$refs.chatBody) {
              this.$refs.chatBody.scrollTop = this.$refs.chatBody.scrollHeight;
            }
          });
        }
      }
    },
    async handleRegenerate() {
      if (this.messages.length === 0) return;
      
      const lastMsg = this.messages[this.messages.length - 1];
      if (!lastMsg.aiResponse) return;
      
      // 设置临时状态
      this.$set(lastMsg, 'isTemporary', true);
      this.$set(lastMsg, 'aiResponse', '');
      
      this.isLoading = true;
      
      try {
        // 重新调用 AI 接口，只发送用户消息，不发送系统提示词
        const aiResponse = await callAIChat(
          lastMsg.mergedImage,
          this.customPrompt, // 使用用户自定义的提示词
          lastMsg.userText,
          {
            model: this.apiConfig.model,
            apiUrl: this.apiConfig.apiUrl
          }
        );
        
        // 更新AI回复并移除临时状态
        this.$set(lastMsg, 'aiResponse', aiResponse);
        this.$set(lastMsg, 'isTemporary', false);
      } catch (error) {
        console.error('重新生成失败:', error);
        // 更新错误信息并移除临时状态
        this.$set(lastMsg, 'aiResponse', `错误: ${error.message}`);
        this.$set(lastMsg, 'isTemporary', false);
      } finally {
        this.isLoading = false;
        
        this.$nextTick(() => {
          if (this.$refs.chatBody) {
            this.$refs.chatBody.scrollTop = this.$refs.chatBody.scrollHeight;
          }
        });
      }
    },
    handleClearChat() {
      // 清空所有聊天记录
      this.messages = [];
      // 同时清空输入框
      this.inputText = '';
    },
    // 新增方法：渲染 Markdown 内容
    renderMarkdown(content) {
      if (!content) return '';
      return marked(content);
    }
  }
};
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--bg);
}

.chat-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--panel);
  border: 1px solid var(--border);
  border-radius: 8px;
  overflow: hidden;
}

.chat-header {
  padding: 12px 16px;
  border-bottom: 1px solid var(--border);
  background: #fafafa;
}

.model-title {
  font-weight: 600;
  font-size: 14px;
}

.chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.empty-state {
  text-align: center;
  color: var(--muted);
  padding: 60px 20px;
}

.empty-state p {
  font-size: 13px;
}

.message-item {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  align-items: flex-start;
}

.user-message {
  flex-direction: row-reverse;
}

.ai-message {
  flex-direction: row;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
}

.message-avatar.user {
  background: #e3f2fd;
}

.message-avatar.ai {
  background: #f0f0f0;
}

.message-content {
  flex: 1;
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-message .message-content {
  align-items: flex-end;
}

.ai-message .message-content {
  align-items: flex-start;
}

.message-bubble {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-width: 100%;
}

.user-bubble {
  background: var(--primary);
  border-radius: 12px;
  border-bottom-right-radius: 4px;
  padding: 12px;
}

.ai-bubble {
  background: #f0f0f0;
  border-radius: 12px;
  border-bottom-left-radius: 4px;
  padding: 12px;
}

.image-group {
  margin-bottom: 0;
}

.merged-image {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  display: block;
}

.message-text {
  padding: 0;
  border-radius: 0;
  font-size: 14px;
  line-height: 1.6;
  word-wrap: break-word;
  max-width: 100%;
}

.user-text {
  background: transparent;
  color: #fff;
  border-bottom-right-radius: 0;
}

.ai-text {
  background: transparent;
  color: var(--text);
  border-bottom-left-radius: 0;
}

.loading-text {
  color: var(--muted);
  font-size: 13px;
  text-align: center;
  padding: 8px;
}

.loading-dots {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
}

.loading-dots span {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
  margin: 0 4px;
  animation: loading 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.temporary-message {
  opacity: 0.7;
}

.chat-input-area {
  padding: 12px 16px;
  border-top: 1px solid var(--border);
  background: #fafafa;
}

.chat-input {
  width: 100%;
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 10px 12px;
  font-size: 13px;
  font-family: inherit;
  resize: none;
  outline: none;
  margin-top: 0;
}

.chat-input:focus {
  border-color: var(--primary);
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-left: 10px;
}

.send-btn {
  background: #ff7a00;
  color: #fff;
  border-color: #ff7a00;
  height: 36px;
  width: 60px;
  text-align: center;
}

.send-btn:hover {
  background: #ff8c1f;
  border-color: #ff8c1f;
  color: #fff;
}

.bottom-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  justify-content: flex-start;
}

.regenerate-btn {
  background: #fff;
  border: 1px solid #1890ff;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 12px;
  color: #1890ff;
  transition: all 0.2s;
}

.regenerate-btn:hover {
  background: #e6f7ff;
  border-color: #40a9ff;
  color: #40a9ff;
}

.clear-chat-btn {
  background: #fff;
  border: 1px solid #ff4d4f;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 12px;
  color: #ff4d4f;
  transition: all 0.2s;
}

.clear-chat-btn:hover {
  background: #fff2f0;
  border-color: #ff7875;
  color: #ff7875;
}

.chat-block {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}
</style>